﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TbDataSync
{
    public partial class Program
    {
        private static FileStream fs = new FileStream(failedDeviceFileName, FileMode.OpenOrCreate);
        private static StreamWriter sw = new StreamWriter(fs);

        public static void RegistListenerOfExit()
        {
            //注册退出监测事件
            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (ctx) =>
            {
                WriteDevices();
                Wait();
            };

            //AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            //{
            //    Log.Debug("appdomain exit");
            //    Wait();
            //};

            //Console.CancelKeyPress += (sender, e) =>
            //{
            //    e.Cancel = true;
            //    Log.Debug("cancle key exit");
            //    Wait();
            //};

        }

        /// <summary>
        /// 记录创建失败的设备
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="err_decode"></param>
        public static void LogFailedDevice(string deviceName, ResponseResultErr err_decode)
        {
            failedFileNum++;
            sw.WriteLine($"设备 {deviceName} 未新建,原因:{err_decode.message}");
            sw.Flush(); fs.Flush();
        }
        
        /// <summary>
        /// 提示未创建设备
        /// </summary>
        public static void WriteDevices()
        {
            if (failedFileNum > 0)
            {
                Log.Debug($"本次运行结果中含有未成功新建的设备，请查看 {failedDeviceFileName}");
            }
        }
    }

}
